<template>
  <div class="material-table">
    <!-- 页面标题与操作栏 -->
    <div class="header-container">
      <h2 class="page-title">材料管理</h2>
      <button class="btn-add" @click="openAddDialog">
        <i class="fa fa-plus"></i> 添加材料
      </button>
    </div>
    
    <!-- 搜索框区域 -->
    <div class="search-container">
      <input
        v-model="searchKeyword"
        placeholder="搜索材料名称/类别/备注"
        @keyup.enter="loadData(1)"
        @blur="loadData(1)"
        class="search-input"
      />
    </div>
    
    <!-- 错误信息提示 -->
    <div v-if="errorMsg" class="error-message">{{ errorMsg }}</div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary" role="status" aria-label="加载中"></div>
    </div>
    
    <!-- 数据内容区域 -->
    <div v-else>
      <!-- 材料表格主体 -->
      <div class="table-container">
        <table class="material-table-content">
          <thead>
            <tr>
              <th>材料ID</th>
              <th>材料名称</th>
              <th>类别</th>
              <th>库存数量</th>
              <th>备注</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="material in materials"
              :key="material.id"
              class="table-row"
              @click="openViewDialog(material)"
            >
              <td>{{ material.id }}</td>
              <td>{{ material.name }}</td>
              <td>{{ material.category || '未分类' }}</td>
              <td :class="material.quantity <= 10 ? 'low-quantity' : ''">{{ material.quantity }} {{ material.quantity <= 10 ? '(不足)' : '' }}</td>
              <td class="remark-cell">{{ material.remark || '-' }}</td>
              <td class="table-actions">
                <button class="btn-icon btn-edit" @click.stop="openEditDialog(material)">
                  <i class="fa fa-edit">编辑</i>
                </button>
                <button class="btn-icon btn-delete" @click.stop="handleDeleteMaterial(material.id)">
                  <i class="fa fa-trash">删除</i>
                </button>
              </td>
            </tr>
            <tr v-if="materials.length === 0" class="empty-row">
              <td colspan="6" class="text-center">未找到相关材料信息</td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页组件 -->
      <div class="pagination-container" v-if="total > 0">
        <div class="pagination-info">
          共 {{ total }} 条记录，当前第 {{ currentPage }} 页
        </div>
        <div class="pagination-buttons">
          <button :disabled="currentPage === 1" @click="handlePageChange(1)">首页</button>
          <button :disabled="currentPage === 1" @click="handlePageChange(currentPage - 1)">上一页</button>
          <button v-for="page in visiblePages" :key="page" 
            :class="currentPage === page ? 'btn-pagination active' : 'btn-pagination'"
            @click="handlePageChange(page)">{{ page }}</button>
          <button :disabled="currentPage === totalPages" @click="handlePageChange(currentPage + 1)">下一页</button>
          <button :disabled="currentPage === totalPages" @click="handlePageChange(totalPages)">末页</button>
        </div>
      </div>
      
      <!-- 空数据提示 -->
      <div class="empty-container" v-else>
        <div class="empty-content">
          <i class="fa fa-inbox text-3xl mb-2 text-gray-300"></i>
          <p class="text-gray-500">未找到相关材料信息</p>
        </div>
      </div>
    </div>
    
    <!-- 添加材料对话框 -->
    <div v-if="addDialogVisible" class="dialog-container" @click.self="addDialogVisible = false">
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>添加材料</h3>
          <button @click="addDialogVisible = false" class="close-btn">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <form class="material-form">
            <div class="form-group">
              <label for="name">材料名称</label>
              <input id="name" type="text" v-model="newMaterial.name" required class="form-input" placeholder="请输入材料名称">
            </div>
            <div class="form-group">
              <label for="category">类别</label>
              <input id="category" type="text" v-model="newMaterial.category" class="form-input" placeholder="请输入类别">
            </div>
            <div class="form-group">
              <label for="quantity">库存数量</label>
              <input id="quantity" type="number" v-model="newMaterial.quantity" required class="form-input" placeholder="请输入库存数量">
            </div>
            <div class="form-group">
              <label for="remark">备注</label>
              <textarea id="remark" v-model="newMaterial.remark" class="form-input" rows="3" placeholder="请输入备注信息"></textarea>
            </div>
          </form>
        </div>
        <div class="dialog-footer">
          <button @click="addDialogVisible = false" class="btn-cancel">取消</button>
          <button @click="saveMaterial" class="btn-save">保存</button>
        </div>
      </div>
    </div>
    
    <!-- 编辑材料对话框 -->
    <div v-if="editDialogVisible" class="dialog-container" @click.self="editDialogVisible = false">
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>编辑材料</h3>
          <button @click="editDialogVisible = false" class="close-btn">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <form class="material-form">
            <div class="form-group">
              <label for="editName">材料名称</label>
              <input id="editName" type="text" v-model="editedMaterial.name" required class="form-input" placeholder="请输入材料名称">
            </div>
            <div class="form-group">
              <label for="editCategory">类别</label>
              <input id="editCategory" type="text" v-model="editedMaterial.category" class="form-input" placeholder="请输入类别">
            </div>
            <div class="form-group">
              <label for="editQuantity">库存数量</label>
              <input id="editQuantity" type="number" v-model="editedMaterial.quantity" required class="form-input" placeholder="请输入库存数量">
            </div>
            <div class="form-group">
              <label for="editRemark">备注</label>
              <textarea id="editRemark" v-model="editedMaterial.remark" class="form-input" rows="3" placeholder="请输入备注信息"></textarea>
            </div>
          </form>
        </div>
        <div class="dialog-footer">
          <button @click="editDialogVisible = false" class="btn-cancel">取消</button>
          <button @click="updateMaterial" class="btn-update">更新</button>
        </div>
      </div>
    </div>
    
    <!-- 查看材料详情对话框 -->
    <div v-if="viewDialogVisible" class="dialog-container" @click.self="viewDialogVisible = false">
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>材料详情</h3>
          <button @click="viewDialogVisible = false" class="close-btn">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <div class="detail-item">
            <span class="detail-label">材料ID：</span>
            <span class="detail-value">{{ viewedMaterial.id }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">材料名称：</span>
            <span class="detail-value">{{ viewedMaterial.name }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">类别：</span>
            <span class="detail-value">{{ viewedMaterial.category || '未分类' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">库存数量：</span>
            <span class="detail-value" :class="viewedMaterial.quantity <= 10 ? 'low-quantity' : ''">
              {{ viewedMaterial.quantity }} {{ viewedMaterial.quantity <= 10 ? '(不足)' : '' }}
            </span>
          </div>
          <div class="detail-item">
            <span class="detail-label">备注：</span>
            <span class="detail-value remark-detail">{{ viewedMaterial.remark || '无备注' }}</span>
          </div>
        </div>
        <div class="dialog-footer">
          <button @click="viewDialogVisible = false" class="btn-close">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';

// 状态管理
const searchKeyword = ref('');        // 搜索关键词
const currentPage = ref(1);           // 当前页码
const pageSize = ref(5);             // 每页显示数量
const total = ref(0);                 // 总记录数
const materials = ref([]);            // 材料数据列表
const loading = ref(false);           // 加载状态
const errorMsg = ref('');             // 错误信息

// 对话框状态
const addDialogVisible = ref(false);      // 添加对话框显示状态
const editDialogVisible = ref(false);     // 编辑对话框显示状态
const viewDialogVisible = ref(false);     // 查看对话框显示状态

// 表单数据
const newMaterial = ref({
  name: '',
  category: '',
  quantity: 0,
  remark: ''
});

const editedMaterial = ref({
  id: null,
  name: '',
  category: '',
  quantity: 0,
  remark: ''
});

const viewedMaterial = ref({});

// 计算总页数
const totalPages = computed(() => Math.ceil(total.value / pageSize.value));

// 计算可见页码（最多显示5个连续页码）
const visiblePages = computed(() => {
  if (totalPages.value <= 5) {
    return Array.from({ length: totalPages.value }, (_, i) => i + 1);
  }
  
  let start = currentPage.value - 2;
  let end = currentPage.value + 2;
  
  if (start < 1) {
    start = 1;
    end = 5;
  } else if (end > totalPages.value) {
    end = totalPages.value;
    start = end - 4;
  }
  
  return Array.from({ length: end - start + 1 }, (_, i) => start + i);
});

// 加载材料数据
const loadData = async (page) => {
  console.group('材料数据加载');
  page = page || currentPage.value;
  loading.value = true;
  errorMsg.value = '';
  
  try {
    const response = await axios.get('/api/materials/page', {
      params: {
        pageNum: page,
        pageSize: pageSize.value,
        keyword: searchKeyword.value
      }
    });
    console.log('响应数据:', response.data);
    const data = response.data.data;
    materials.value = data.records || [];
    total.value = data.total || 0;
    currentPage.value = page;
  } catch (error) {
    console.error('加载材料数据失败', error);
    errorMsg.value = '加载数据失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 打开添加材料对话框
const openAddDialog = () => {
  newMaterial.value = {
    name: '',
    category: '',
    quantity: 0,
    remark: ''
  };
  addDialogVisible.value = true;
};

// 保存新材料
const saveMaterial = async () => {
  if (!newMaterial.value.name || newMaterial.value.quantity === 0) {
    errorMsg.value = '材料名称和库存数量为必填项';
    return;
  }
  
  try {
    const response = await axios.post('/api/materials/newMaterial', newMaterial.value);
    addDialogVisible.value = false;
    loadData();
    errorMsg.value = '材料添加成功';
    
    setTimeout(() => {
      errorMsg.value = '';
    }, 3000);
  } catch (error) {
    console.error('添加材料失败', error);
    errorMsg.value = error.response?.data?.message || '材料添加失败，请重试';
  }
};

// 打开编辑材料对话框
const openEditDialog = (material) => {
  editedMaterial.value = { ...material };
  editDialogVisible.value = true;
};

// 更新材料
const updateMaterial = async () => {
  if (!editedMaterial.value.name || editedMaterial.value.quantity === 0) {
    errorMsg.value = '材料名称和库存数量为必填项';
    return;
  }
  
  try {
    await axios.put('/api/materials', editedMaterial.value);
    editDialogVisible.value = false;
    loadData();
    errorMsg.value = '材料更新成功';
    
    setTimeout(() => {
      errorMsg.value = '';
    }, 3000);
  } catch (error) {
    console.error('更新材料失败', error);
    errorMsg.value = error.response?.data?.message || '材料更新失败，请重试';
  }
};

// 打开查看材料对话框
const openViewDialog = (material) => {
  viewedMaterial.value = { ...material };
  viewDialogVisible.value = true;
};

// 处理删除材料
const handleDeleteMaterial = async (id) => {
  if (confirm('确定要删除该材料吗？此操作不可恢复')) {
    try {
      await axios.delete(`/api/materials/${id}`);
      loadData();
      errorMsg.value = '材料删除成功';
    } catch (error) {
      console.error('删除材料失败', error);
      errorMsg.value = error.response?.data?.message || '材料删除失败，请重试';
    }
  }
};

// 处理页码变更
const handlePageChange = (page) => {
  if (page < 1 || page > totalPages.value) return;
  loadData(page);
};

// 组件挂载时加载初始数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.error-message {
  color: #e74c3c;
  margin-bottom: 12px;
  font-size: 14px;
}

/* 基础容器样式 */
.material-table {
  width: 100%;
  padding: 24px;
  box-sizing: border-box;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 搜索框样式 */
.search-container {
  margin-bottom: 20px;
  position: relative;
}

.search-input {
  width: 100%;
  padding: 12px 12px;
  padding-left: 32px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.search-input:focus {
  outline: none;
  border-color: #2980b9;
  box-shadow: 0 0 0 2px rgba(41, 128, 185, 0.2);
}

.search-input::placeholder {
  color: #95a5a6;
}

/* 按钮样式 */
.btn-add {
  background-color: #2980b9;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: background-color 0.3s;
}

.btn-add:hover {
  background-color: #2573a8;
}

/* 加载状态样式 */
.loading-container {
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #95a5a6;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  overflow-x: auto;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 表格基础样式 */
.material-table-content {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.material-table-content th,
.material-table-content td {
  border: 1px solid #e0e0e0;
  padding: 12px;
  text-align: left;
  font-size: 14px;
  word-break: break-word;
}

.material-table-content th {
  background-color: #f5f5f5;
  font-weight: bold;
  color: #2c3e50;
}

.table-row {
  cursor: pointer;
  transition: background-color 0.2s;
}

.table-row:hover {
  background-color: #f0f8ff;
}

.low-quantity {
  color: #e74c3c;
}

.remark-cell {
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.empty-row {
  color: #7f8c8d;
  font-style: italic;
  text-align: center;
}

/* 操作按钮样式 */
.table-actions {
  display: flex;
  gap: 4px;
  justify-content: center;
}

.btn-icon {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.btn-icon i {
  font-size: 14px;
}

/* 编辑按钮 */
.btn-edit {
  background-color: #2ecc71;
  color: white;
  box-shadow: 0 2px 4px rgba(46, 204, 113, 0.3);
}

.btn-edit:hover {
  background-color: #27ae60;
  box-shadow: 0 4px 8px rgba(46, 204, 113, 0.4);
  transform: translateY(-1px);
}

/* 删除按钮 */
.btn-delete {
  background-color: #e74c3c;
  color: white;
  box-shadow: 0 2px 4px rgba(231, 76, 60, 0.3);
}

.btn-delete:hover {
  background-color: #c0392b;
  box-shadow: 0 4px 8px rgba(231, 76, 60, 0.4);
  transform: translateY(-1px);
}



/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  font-size: 14px;
  color: #555;
}

.pagination-info {
  flex: 1;
}

.pagination-buttons {
  display: flex;
  gap: 4px;
}

.pagination-buttons button {
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  background-color: white;
  transition: all 0.3s;
  font-size: 14px;
  min-width: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-buttons button:hover:not(:disabled) {
  border-color: #2980b9;
  color: #2980b9;
}

.pagination-buttons button:disabled {
  border-color: #eee;
  color: #aaa;
  cursor: not-allowed;
}

.btn-pagination.active {
  background-color: #2980b9;
  color: white;
  border-color: #2980b9;
}

/* 空数据提示 */
.empty-container {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #95a5a6;
}

.empty-content {
  text-align: center;
}

/* 对话框样式 */
.dialog-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 6px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.dialog-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.close-btn {
  border: none;
  background: none;
  font-size: 20px;
  cursor: pointer;
  color: #95a5a6;
}

.dialog-body {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.detail-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.detail-label {
  font-weight: bold;
  color: #555;
  width: 80px;
  display: inline-block;
}

.detail-value {
  color: #333;
}

.remark-detail {
  white-space: pre-wrap;
}

.material-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  color: #555;
  font-size: 14px;
}

.form-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-input[type="number"] {
  width: 100px;
}

textarea.form-input {
  resize: vertical;
}

.dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn-cancel, .btn-close {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  background-color: white;
  transition: all 0.3s;
}

.btn-save, .btn-update {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  color: white;
  transition: all 0.3s;
}

.btn-save {
  background-color: #2980b9;
}

.btn-update {
  background-color: #27ae60;
}

.btn-save:hover {
  background-color: #2573a8;
}

.btn-update:hover {
  background-color: #2ecc71;
}

.btn-cancel:hover, .btn-close:hover {
  border-color: #95a5a6;
  color: #555;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .material-table {
    padding: 12px;
  }
  
  .header-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .pagination-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .remark-cell {
    max-width: 100px;
  }
  
  .dialog-content {
    width: 90%;
  }
}

/* 小屏幕优化 */
@media (max-width: 576px) {
  .table-actions {
    gap: 2px;
  }
  
  .btn-icon {
    width: 24px;
    height: 24px;
  }
  
  .btn-icon i {
    font-size: 12px;
  }
  
  .form-input[type="number"] {
    width: 80px;
  }
}
</style>